<template>
  <el-dialog title="Delivery Address" width="600px" :visible.sync="dialogFlag" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" @close="handleClose" center>
    <el-form style="margin-top: -20px" :model="dialogForm" :rules="rules" ref="dialogFormRef">
      <el-row>
        <el-col :span="11">
          <el-form-item prop="name" :model="dialogForm">
            <el-input v-model="dialogForm.name" placeholder="name" />
          </el-form-item>
        </el-col>
        <el-col :span="11" :push="2">
          <el-form-item prop="phone" class="is-required">
            <el-input v-model="dialogForm.phone" placeholder="contact number" :maxlength="20" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="email">
            <el-input v-model="dialogForm.email" placeholder="email" />
          </el-form-item>
        </el-col>
        <el-col :span="11" :push="2">
          <el-form-item prop="zipCode">
            <el-input v-model="dialogForm.zipCode" placeholder="ZIP Code" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item prop="countryCode">
        <VueCountryIntl v-model="dialogForm.countryCode" placeholder="please select country" @onChange="countryChange"></VueCountryIntl>
      </el-form-item>

      <el-form-item prop="state">
        <el-input v-model="dialogForm.state" placeholder="State/Province/Region" />
      </el-form-item>

      <el-form-item prop="city">
        <el-input v-model="dialogForm.city" placeholder="city" />
      </el-form-item>

      <el-form-item prop="address">
        <el-input type="textarea" v-model="dialogForm.address" placeholder="address" :autosize="{ minRows: 6, maxRows: 6}" />
      </el-form-item>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="isDefault" label="isDefault:">
            <el-radio-group v-model="dialogForm.isDefault">
              <el-radio label="0">yes</el-radio>
              <el-radio label="1">no</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <div class="btn-box">
          <el-button type="primary" style="width: 170px;" @click="handleSubmit()">Confirm</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
let VueCountryIntl
if (process.client) {
  VueCountryIntl = require('vue-country-intl') // 这里的意思就是写你在 window 对象上的操作，可以翻译为下面这段代码
  require('vue-country-intl/lib/vue-country-intl.css')
}
const defaultForm = {
  name: '',
  phone: '',
  email: '',
  zipCode: '', // 邮编
  countryCode: null,
  country: '',
  state: '',
  city: '',
  address: '',
  isDefault: '0', // 是否默认（0是1否）
  status: '0', // 状态（0正常 1停用）
  addressType: '0', // 地址类型（0收货地址1发货地址）
}
export default {
  props: {
    flag: {
      default: false
    },
    rowInfo: {
      default: () => ({})
    }
  },
  components: {
    VueCountryIntl: VueCountryIntl
  },
  watch: {
    flag: {
      handler (val) {
        this.dialogFlag = val
        if (val) {
          this.init()
        }
      }
    }
  },
  data () {
    const validateEMail = (rule, value, callback) => {
      const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (value === '') {
        callback(new Error('This field is required!'))
      } else if (!reg.test(value)) {
        callback(new Error('Email invalid'))
      } else {
        callback()
      }
    }
    return {
      dialogFlag: false,
      dialogForm: defaultForm,
      rules: {
        name: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        phone: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        email: [{ required: true, validator: validateEMail, trigger: 'blur' }],
        countryCode: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        state: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        city: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        address: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
      }
    }
  },
  methods: {
    async init () {
      if (this.rowInfo.addressId) {
        const res = await this.$axios.get(`web/address/${this.rowInfo.addressId}`)
        if (res.code == 200) {
          console.log('detail', res)
          this.dialogForm = res.data
          this.dialogForm.countryCode = res.data.country && res.data.country.split(',')[0]
        }
      }
    },
    countryChange (obj) {
      this.dialogForm.country = `${obj.dialCode},${obj.name}`
    },
    handleClose () {
      this.dialogForm = {
        ...defaultForm
      }
      this.$nextTick(() => {
        this.$refs.dialogFormRef.resetFields()
      })
      this.dialogFlag = false
      this.$emit('close')
    },
    handleSubmit () {
      this.$refs.dialogFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const options = {
          ...this.dialogForm,
          userId: this.$local.getItem('user').userId
        }
        if (this.dialogForm.addressId) { // 编辑
          const res = await this.$axios.put('web/address', options)
          if (res.code == 200) {
            this.$message.success('update address success!')
            this.handleClose()
            this.$emit('refresh')
          }
        } else { // 添加
          const res = await this.$axios.post('web/address', options)
          if (res.code == 200) {
            this.$message.success('add address success!')
            this.handleClose()
            this.$emit('refresh')
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.w-300 {
  width: 300px;
}
.btn-box {
  width: 100%;
  display: flex;
  justify-content: center;
}
::v-deep .vue-country-intl .country-intl-label {
  box-sizing: border-box;
  padding: 0 10px;
}
::v-deep .vue-country-item {
  padding: 0 10px;
}
</style>
